package com.example.lib_patrol.add

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.example.lib_common.mvi.BaseActivity
import com.example.lib_patrol.R
import com.example.lib_patrol.databinding.ActivityPointBinding
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
import kotlin.collections.ArrayList


@Route(path = "/patrol/AddPatrolActivity")
class AddPatrolActivity :BaseActivity<ActivityPointBinding,AddPatrolViewModel>() {
    val pointAdapter = PointAdapter()
    var allList : ArrayList<PointEntity> = ArrayList()
    var allGroupList : ArrayList<GroupEntity> = ArrayList()
    var allTeam : ArrayList<String> = ArrayList()
    var selectTeam = ""
    var pointList : ArrayList<RowEntity> = ArrayList()
    override fun createVM(): AddPatrolViewModel {
        return  AddPatrolViewModel()
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityPointBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        v.backBtn.setOnClickListener { finish() }
        vm.requestAll()
        vm.requestAllGroup()
        bindState()
        v.clearPoint.setOnClickListener {
            for (pointEntity in allList) {
                pointEntity.pChecked=false
            }
            pointAdapter.notifyDataSetChanged()
        }
        v.sureAddPatrol.setOnClickListener {
            var pGroupId =0L
            if (allGroupList.size>0){
                for (groupEntity in allGroupList) {
                    if (groupEntity.gName==selectTeam){
                        pGroupId=groupEntity.gId
                    }
                }
            }
            if (pointList.size>0){
                val gson = Gson()
                val toJson = gson.toJson(pointList)
                val map : HashMap<String,Any> = HashMap()
                map["pEnd"]=""+System.currentTimeMillis()
                map["pGroupId"]=pGroupId
                map["pPoint"]=toJson
                map["pStart"]=""+System.currentTimeMillis()
                map["pTime"]=""+System.currentTimeMillis()
                map["pType"]=0
                map["pUserId"]=SPUtils.getInstance().getInt("uId")
                vm.requestAddPatrol(map)
            }
        }
    }
    private fun bindState() {
        lifecycleScope.launch(Dispatchers.Main){
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.uiStateFlow.collect{
                    if (it.entity.statuesCode==200){
                        allList= it.entity.values as ArrayList<PointEntity>
                        bindAdapter()
                    }
                    if (it.entity2.statuesCode==200){
                        allGroupList= it.entity2.values as ArrayList<GroupEntity>
                        LogUtils.e("====${allGroupList.size}")
                        if (allGroupList!=null){
                            for (groupEntity in allGroupList) {
                                allTeam.add(groupEntity.gName.toString())
                                bindSpanner()
                            }
                        }
                    }
                    if (it.entity1.msg=="成功"){
                        finish()
                    }
                }
            }
        }
    }

    private fun bindSpanner() {
        val adapter = ArrayAdapter(this,R.layout.item_team,R.id.item_team,allTeam)
        v.spinner.adapter=adapter
        v.spinner.onItemSelectedListener=object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                selectTeam = p0!!.getItemAtPosition(p2).toString()
            }
            override fun onNothingSelected(p0: AdapterView<*>?) {
                TODO("Not yet implemented")
            }
        }
    }

    private fun bindAdapter() {
        val layoutManager = GridLayoutManager(this,3)
        layoutManager.orientation=RecyclerView.VERTICAL
        v.patrolPointRecycler.layoutManager=layoutManager
        v.patrolPointRecycler.adapter=pointAdapter
        pointAdapter.setNewInstance(allList)
        pointAdapter.setOnItemClickListener { adapter, view, position ->
            val data = adapter.data as ArrayList<PointEntity>
            data.get(position).pChecked=!data.get(position).pChecked
            pointAdapter.notifyDataSetChanged()
            var flag =-1
            if (data[position].pChecked==true){
                val rowEntity =RowEntity()
                rowEntity.pointName=data[position].pointName.toString()
                rowEntity.pointId=data[position].pointId
                pointList.add(rowEntity)
            }else{
//                    until不包含末尾
                for (i in 0 until pointList.size){
                    if (pointList[i].pointId==data[position].pointId){
                        flag=i
                    }
                }
            }
            if (flag>-1){
                pointList.removeAt(flag)
            }
        }
    }
}